<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class CarouselController extends Controller
{
	//列表页
    public function getIndex(Request $request)
    {
    	if($request->input('name')){
    		$cate = DB::table('carousel')
    		->where('name','like','%'.$request->input('name').'%')
    		->paginate(5);
    	}else{
        	$cate = DB::table('carousel')
    		->where('name','like','%'.$request->input('name').'%')
    		->paginate(5);
    	}
    	$data = $request->all();
    	return view('admin.carousel.index',['cate'=>$cate,'data'=>$data]);
    }
    //添加
    public function getAdd()
    {
    	return view('admin.carousel.add');
    }
    //执行添加
    public function postInsert(Request $request)
    {
    	if(!$request->hasFile('pic')){
       		exit('上传文件为空！');
	    }if(!$request->hasFile('pic')){
	        exit('上传文件为空！');
	    }
    	$file = $request->file('pic');
	    if(!$file->isValid()){
	        exit('文件上传出错！');
	    }
	    $suffix = $request->file('pic')->getClientOriginalExtension();
    	$picname = MD5(time()).'.'.$suffix;
    	$res = $file->move('./uploads',$picname);
	    if($res){
	    	$data['name'] = $request->input('name');
	    	$data['img'] = $picname;
	    	$data['date'] = date('Y-m-d H:i:s',time());
	    	$rs = DB::table('carousel')->insert($data);
			return redirect('/admin/carousel/index')->with('success','添加成功');
	    }else{
			return back();
	    }
	}
	//删除
	public function getDelete($id)
	{
		$r = DB::table('carousel')->where('id',$id)->delete();
		if($r){
			return back()->with('success','删除成功');
		}else{
			return back()->with('error','删除失败');
		}
	}
	//修改
	public function getEdit($id)
	{
		$catesinfo = DB::table('carousel')->where('id',$id)->first();
		return view('admin.carousel.edit',['catesinfo'=>$catesinfo]);
	}
	//执行修改
	public function postUpload(Request $request)
	{
		if(!$request->hasFile('pic')){
       		exit('上传文件为空！');
	    }if(!$request->hasFile('pic')){
	        exit('上传文件为空！');
	    }
    	$file = $request->file('pic');
	    if(!$file->isValid()){
	        exit('文件上传出错！');
	    }
	    $suffix = $request->file('pic')->getClientOriginalExtension();
    	$picname = MD5(time()).'.'.$suffix;
    	$res = $file->move('./uploads',$picname);
	    if($res){
	    	$id = $request->input('id');
	    	$data['name'] = $request->input('name');
	    	$data['img'] = $picname;
	    	$data['date'] = date('Y-m-d H:i:s',time());
	    	$rs = DB::table('carousel')->where('id',$id)->update($data);
			return redirect('/admin/carousel/index')->with('success','修改成功');
	    }else{
			return back()->withInput();
	    }
	}
}
